package main

import (
	"context"
	"fmt"
	ezToken "gitee.com/jinmingzhi/eth-learn/5day/build"
	"gitee.com/jinmingzhi/eth-learn/pkg/ethtool"
	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/common"
	"math/big"
)

var (
	contractAddressHex = "0xCfEB869F69431e42cdB54A4F4f105C19C080A601"
	ownerPriKey        = "0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"
	toAddressHex       = "0xe03ea8624C8C5987235048901fB614fDcA89b117"
	url                = "http://localhost:8545"
	ctx                = context.Background()
)

func main() {
	client, err := ethtool.Dial(url)
	assert(err)

	// contract address
	contractAddress := common.HexToAddress(contractAddressHex)
	inst, err := ezToken.NewEzToken(contractAddress, client)
	assert(err)

	// owner private
	credential, err := ethtool.HexToCredential(ownerPriKey)
	assert(err)
	chainId, err := client.NetVersion(ctx)
	assert(err)
	txOpts, err := bind.NewKeyedTransactorWithChainID(credential.PrivateKey, chainId)
	assert(err)

	// transaction to address
	toAddress := common.HexToAddress(toAddressHex)

	tx, err := inst.Transfer(txOpts, toAddress, big.NewInt(300))
	assert(err)
	fmt.Println("transfer token txid: ", tx.Hash().Hex())

	// owner balance
	ownerBalance, err := inst.BalanceOf(&bind.CallOpts{
		From: credential.Address,
	}, credential.Address)
	assert(err)
	fmt.Println("owner balance:", ownerBalance)

	// to address balance
	toAddressBalance, err := inst.BalanceOf(&bind.CallOpts{
		From: credential.Address,
	}, toAddress)
	assert(err)
	fmt.Println("toAddress balance:", toAddressBalance)
}

func assert(err error) {
	if err != nil {
		panic(err)
	}
}
